package com.mofei.mall04_fileupload.service.serviceImpl;

import com.mofei.mall04_fileupload.common.util.ImgUtil;
import com.mofei.mall04_fileupload.common.util.PdfUtil;
import com.mofei.mall04_fileupload.service.FileUploadService;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    //选择文件进行图转pdf
    public void uploadFile(String Type, MultipartFile[] pictureFiles){
        try{
            if(pictureFiles!=null&&pictureFiles.length>0&&StringUtils.isNotBlank(pictureFiles[0].getOriginalFilename())){

                Integer angel = 270;
                String[] files = new String[100];
                String mergeFileName = "pdf_"+String.valueOf(System.currentTimeMillis()+".pdf");//设置pdf名为当前时间戳
                File folderPath = new File(Type);// 若不存在，则创建文件夹
                if (!folderPath.exists()) {
                    folderPath.mkdirs();
                }
                //循环操作图片，获取bufferedImage流
                for (int i = 0; i < pictureFiles.length; i++) {
                    if (!pictureFiles[i].isEmpty()) {

                        BufferedImage bufferedImage = null;//创建空的BufferedImage对象
                        File _img_file_ = MultipartFileToFile(pictureFiles[i]);
                        BufferedImage src = ImageIO.read(_img_file_);//对图片文件进行读取（格式应为GIF, PNG, or JPEG）
                        //获取图片的长宽，计算长宽比
                        BigDecimal height = BigDecimal.valueOf(src.getHeight());
                        BigDecimal width = BigDecimal.valueOf(src.getWidth());
                        BigDecimal bd = height.divide(width,4,BigDecimal.ROUND_CEILING);
                        //设置标准长宽比
                        BigDecimal theValue = BigDecimal.valueOf(1.1700);
                        //判断图片长宽比是否小于标准长宽比，若是 进行转换
                        if (bd.compareTo(theValue) == -1 ) {
                            System.out.println("转换中 ...");
                            //将图片旋转270°，不进行缩放，执行calcScale方法
                            bufferedImage = Thumbnails.of(src).rotate(angel).scale(1).asBufferedImage();
                            bufferedImage = ImgUtil.calcScale(bufferedImage);
                        }else {
                            bufferedImage = ImgUtil.calcScale(src);
                            System.out.println("宽高比合适,跳过 ...");
                        }

                        if(bufferedImage==null){
                            continue;//
                        }
                        String pdffile = PdfUtil.Img2PDF(_img_file_.getName(),bufferedImage,Type);
                        files[i] = pdffile;
                    }

                }
                PdfUtil.mergePDF(files,Type,mergeFileName);
                PdfUtil.deletePDF(files,mergeFileName);
            }
        }catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //转换文件夹下所有的图片
    public void uploadByFolder(String folder,String Type){
        try {
            Integer angel = 270;
            String[] files = new String[100];
            ImgUtil imageUtil = new ImgUtil();
            String mergeFileName = "pdf_"+String.valueOf(System.currentTimeMillis()+".pdf");//设置pdf名为当前时间戳
            //初始化文件地址和导出地址
            File uploadPath = new File(folder);
            File downloadPath = new File(Type);// 若不存在，则创建文件夹
            if (!downloadPath.exists()) {
                downloadPath.mkdirs();
            }
            File[] folderFiles = uploadPath.listFiles();//获得上传文件夹内的文件名
            for (int i = 0;i<folderFiles.length;i++){
                files[i] = folderFiles[i].getName();
            }
            for (int i=0;i<files.length;i++) {
                StringBuffer sb = new StringBuffer();
                sb.append(files[i]);
                String file =folder+"/"+ sb;

                if (file.toLowerCase().endsWith(".png")
                        || file.toLowerCase().endsWith(".jpg")
                        || file.toLowerCase().endsWith(".gif")
                        || file.toLowerCase().endsWith(".jpeg")
                        || file.toLowerCase().endsWith(".gif")) {

                    BufferedImage bi = imageUtil.rotateImage(file);
                    if (bi==null){ continue;}
                    String pdffile = PdfUtil.Img2PDF(file,bi,folder);
                    files[i] = pdffile;
                }
            }
            PdfUtil.mergePDF(files,Type,mergeFileName);
            PdfUtil.deletePDF(files,mergeFileName);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    /**将MultipartFile转换为File**/
    public static File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
